<template>
  <div class="buy">
    <div class="top">
      <div class="logo">
        <img src="./images/logoen.png" />
      </div>
      <div class="notice">
        <van-notice-bar
          left-icon="volume-o"
          color="#0051c7"
          background="#fff"
          :scrollable="false"
        >
          <van-swipe
            vertical
            class="notice-swipe"
            :autoplay="3000"
            :show-indicators="false"
          >
            <van-swipe-item v-for="(item, index) in noticeList"
              >{{ item.title }}<span class="iconfont icon-youjiantou"></span
            ></van-swipe-item>
          </van-swipe>
        </van-notice-bar>
      </div>
    </div>
    <div class="container">
      <div class="side-menu" ref="scroll">
        <ul class="navmenu">
          <li
            v-for="(item, index) in sidebarList"
            :key="index"
            @click="isActive(index)"
            :class="index === currentIndex ? 'active' : ''"
          >
            {{ item.title }}
          </li>
        </ul>
      </div>
      <div class="goods" ref="scrollGoods">
        <Goods :goodsList="goodsList" />
      </div>
    </div>
    <!-- 底部购物车遮罩层 -->
    <div class="cart-dialog">
      <van-popup
        v-model="orderShow"
        round
        position="bottom"
        :style="{ height: height }"
        get-container=".cart-dialog"
      >
        <div class="pop-header">
          <van-checkbox
            class="header-text"
            v-model="allChecked"
            icon-size="18px"
            @click="checkAllGoods"
            >已选购商品({{ content }}件)</van-checkbox
          >
          <van-icon name="delete-o" class="pop-icon" @click="delAllGoods" />
        </div>
        <div class="pop-content">
          <ul ref="popUl">
            <li v-for="(item, index) in shopCartList" :key="index">
              <van-checkbox
                class="header-text"
                icon-size="18px"
                v-model="item.checked"
                @click="checkItemGoods(index)"
              >
              </van-checkbox>
              <div class="goods-pic">
                <img :src="item.goods_img" />
              </div>
              <div class="check-goodsInfo">
                <div class="check-goods-title">{{ item.goods_name }}</div>
                <div class="check-goods-type">{{ item.goods_choose }}</div>
                <div class="check-goods-price">
                  ¥<span>{{ item.goods_price }}</span>
                </div>
              </div>
              <div class="check-num">
                <div class="btn-reduce" @click="goodsNumReduce(index, item.id)">
                  <van-icon name="minus" />
                </div>
                <div class="num">{{ item.goods_num }}</div>
                <div class="btn-add" @click="goodsNumAdd(index)">
                  <van-icon name="plus" />
                </div>
              </div>
            </li>
          </ul>
        </div>
      </van-popup>
    </div>
    <!-- 底部购物车结算部分 -->
    <div class="tab-cart" v-if="cartShow">
      <div class="cart-content" @click="orderInfo">
        <div class="img-cart">
          <img src="./images/cartlogo.png" />
        </div>
        <div class="badge">
          <van-badge :content="content" />
        </div>
        <div class="pirce">¥<span class="num">{{ total }}</span></div>
      </div>
      <div class="pay" @click="goPay">结算</div>
    </div>
    <Tabbar />
  </div>
</template>

<script>
import BScroll from "@better-scroll/core";
import SideMenu from "@/components/SideMenu";
import Goods from "@/components/Goods";
import MouseWheel from "@better-scroll/mouse-wheel";
import { Toast } from 'vant';
import {
  reqGetGoodsList,
  reqGetShopCart,
  reqDelShopCart,
  reqDelAllShopCart,
  reqAddOrder
} from "@/api";
BScroll.use(MouseWheel);
export default {
  components: {
    SideMenu,
    Goods,
  },
  data() {
    return {
      noticeList: [
        { title: "茶百道 🍵  | 冬季热饮" },
        { title: "美团团购优惠" },
        { title: "小T1an呐" },
      ],
      sidebarList: [
        { id: 1, active: true, title: "新品推荐" },
        { id: 2, active: false, title: "时令水果茶" },
        { id: 3, active: false, title: "坦洋工夫茶" },
        { id: 4, active: false, title: "超人气奶茶" },
        { id: 5, active: false, title: "芝心薯薯" },
        { id: 6, active: false, title: "冷萃茶" },
        { id: 7, active: false, title: "生酪系列" },
        { id: 8, active: false, title: "加料" },
        { id: 9, active: false, title: "保温袋" },
      ],
      active: true,
      goodsList: [],
      scrollY: 0,
      tops: [],
      scroll: "",
      scrollGoods: "",
      orderShow: false,
      allChecked: true,
      height: "100px",
      shopCartList: [],
      cartShow: false
    };
  },
  mounted() {
    this.getGoodsList();
    this.getShopCart();
  },
  computed: {
    // 计算当前分类的下标
    currentIndex() {
      // 得到条件数据
      let { scrollY, tops } = this;
      // 根据条件计算产生一个结果
      // findIndex方法常用来查找数组中满足条件的第一项元素的下标
      // 返回的是满足条件的第一项元素的下标，这要注意的是findIndex会给数组中的每一项执行一个函数来判断是否满足表达式，如果满足条件后，剩下的元素则不再执行
      let index = tops.findIndex((top, index) => {
        // scrollY要大于等于当前top值，还要小于下一个top
        // tops数据：[0, 80, 160, 240, 320, 400, 480, 560, 640, 720, 800]
        return scrollY >= top && scrollY < tops[index + 1];
      });
      // 返回结果
      return index;
    },
    total() {
      let orderList = [];
      this.shopCartList.forEach(item => {
        if (item.checked) {
          orderList.push(item);
        }
      })
      let total = 0;
      orderList.forEach(item => {
        let {goods_price, goods_num} = item;
        total += goods_price * goods_num;
      })
      return total;
    },
    content() {
      let orderList = [];
      this.shopCartList.forEach(item => {
        if (item.checked) {
          orderList.push(item);
        }
      })
      return orderList.length;
    }
  },
  methods: {
    // 初始化滚动
    _initScroll() {
      this.scroll = new BScroll(this.$refs.scroll, {
        mouseWheel: true,
        scrollY: true,
        click: true,
      });
      this.scrollGoods = new BScroll(this.$refs.scrollGoods, {
        mouseWheel: true,
        scrollY: true,
        click: true,
        probeType: 3,
      });
      this.scrollGoods.on("scroll", (position) => {
        // console.log(position.x, position.y);
        this.scrollY = Math.abs(Math.round(position.y));
      });
      // 滚动结束的监听
      this.scrollGoods.on("scrollEnd", (position) => {
        this.scrollY = Math.abs(Math.round(position.y));
      });
    },
    isActive(index) {
      const scrollY = this.tops[index];
      this.scrollY = scrollY;
      // scrollTo(x, y, 动画时间)
      this.scrollGoods.scrollTo(0, -scrollY, 300);
    },
    orderInfo() {
      this.orderShow = true;
      this.$nextTick(() => {
        let popHeight = this.$refs.popUl.clientHeight + 155;
        this.height = popHeight > 355 ? 355 + "px" : popHeight + "px";
        new BScroll(".pop-content", {
          mouseWheel: true,
          scrollY: true,
          click: true,
          probeType: 3,
        });
      });
    },
    async goPay() {
      // 要提交的订单
      let orderList = [];
      this.shopCartList.forEach(item => {
        if (item.checked) {
          orderList.push(item);
        }
      })
      if (orderList.length === 0) {
        Toast('请至少选择一杯饮品再支付哦～')
        return;
      }
      let obj = {
        user_id: this.$store.state.login.userInfo.id,
        goods_info: JSON.stringify(orderList),
        total: this.total
      }
      let res = await reqAddOrder(obj);
      if (res.status === 200) {
        Toast('订单提交成功');
        this.$router.push("/pay");
      }
    },
    async getGoodsList() {
      let res = await reqGetGoodsList();
      if (res.status === 200) {
        this.goodsList = res.data;
      }
    },
    async getShopCart() {
      let user_id = this.$store.state.login.userInfo.id;
      let res = await reqGetShopCart({ user_id });
      if (res.status === 200) {
        this.cartShow = true;
        res.data.forEach((item) => {
          item.checked = true;
        });
        this.shopCartList = res.data;
      }
    },
    async goodsNumReduce(index, id) {
      if (this.shopCartList[index].goods_num > 1) {
        this.shopCartList[index].goods_num -= 1;
      } else {
        // 发请求删除数据，容器高度减小
        let res = await reqDelShopCart({ id });
        if (res.status === 200) {
          this.$nextTick(() => {
            this.getShopCart();
            if (this.shopCartList.length === 2) {
              this.height = "255px";
            } else if (this.shopCartList.length === 1) {
              this.orderShow = false;
              this.cartShow = false;
            }
          });
        }
      }
    },
    goodsNumAdd(index) {
      this.shopCartList[index].goods_num =
        Number(this.shopCartList[index].goods_num) + 1;
    },
    async delAllGoods() {
      let user_id = this.$store.state.login.userInfo.id;
      let res = await reqDelAllShopCart({ user_id });
      if (res.status === 200) {
        this.orderShow = false;
        this.cartShow = false;
      }
    },
    checkAllGoods() {
      if (!this.allChecked) {
        this.shopCartList.forEach(item => {
          item.checked = false;
        })
      } else {
        this.shopCartList.forEach(item => {
          item.checked = true;
        })
      }
    },
    checkItemGoods(index) {
      if (!this.shopCartList[index].checked) {
        this.allChecked = false;
      } else {
        let allArr = [];
        this.shopCartList.forEach(item => {
          allArr.push(item.checked);
        })
        let flag = allArr.indexOf(false);
        if (flag === -1) {
          this.allChecked = true;
        }
      }
    }
  },
  watch: {
    goodsList(val) {
      this.$nextTick(() => {
        this._initScroll();
      });
    }
  },
};
</script>

<style>
.notice-swipe {
  height: 40px;
  line-height: 40px;
}
</style>

<style lang="less" scoped>
.buy {
  display: flex;
  flex-direction: column;
}

.top {
  width: 100%;
  height: 90px;
  position: fixed;
  top: 0;
  background-color: #fff;

  .logo {
    height: 50px;
    padding-left: 10px;
    display: flex;
    border-bottom: 1px solid #e8e7e7;
    align-items: center;

    img {
      width: 150px;
      height: 40px;
    }
  }

  .notice {
    font-weight: bold;
    border-bottom: 1px solid #e8e7e7;
  }
}

.container {
  padding-top: 90px;
  padding-bottom: 50px;
  box-sizing: border-box;
  height: 100vh;
  display: flex;

  .side-menu {
    width: 100px;
    height: 100%;
    overflow: hidden;

    ul {
      padding-bottom: 50px;
      li {
        width: 100px;
        height: 80px;
        display: flex;
        font-size: 14px;
        align-items: center;
        justify-content: center;
        color: #666666;
      }

      .active {
        background-color: #fff;
      }
    }
  }

  .goods {
    flex: 1;
    height: 100%;
    padding: 0 10px 0;
    background-color: #fff;
    box-sizing: border-box;
    overflow: hidden;
  }
}
.tab-cart {
  width: 100%;
  height: 60px;
  background-color: #fff;
  position: fixed;
  left: 0;
  bottom: 50px;
  padding: 0 10px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  border-top: 1px solid #e8e7e7;
  border-bottom: 1px solid #e8e7e7;
  .img-cart {
    width: 70px;
    height: 70px;
    position: absolute;
    bottom: 0;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .badge {
    position: absolute;
    left: 75px;
    top: 10px;
  }
  .pirce {
    margin-left: 90px;
    font-weight: 500;
    font-size: 16px;
    .num {
      font-size: 18px;
      margin-left: 3px;
    }
  }
  .pay {
    width: 100px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: auto;
    border-radius: 20px;
    font-size: 15px;
    color: #fff;
    background-color: #0151c6;
  }
}
.cart-content {
  height: 100%;
  display: flex;
  align-items: center;
}
.cart-dialog {
  position: fixed;
  left: 0;
  bottom: 110px;
  .pop-header {
    height: 45px;
    width: 100%;
    padding: 0 15px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #e8e7e7;
    .header-text {
      font-size: 13px;
    }
    .pop-icon {
      font-size: 18px;
      color: #646566;
    }
  }
  .pop-content {
    max-height: 200px;
    overflow: hidden;
    ul {
      padding: 0 15px;
      box-sizing: border-box;
      li {
        width: 100%;
        height: 100px;
        background-color: #fff;
        padding: 15px 0;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        border-bottom: 1px solid #e8e7e7;
        .goods-pic {
          width: 60px;
          height: 60px;
          margin: 0 10px;
          text-align: center;
          img {
            height: 100%;
          }
        }
        .check-goodsInfo {
          height: 100%;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          .check-goods-title {
            font-size: 15px;
          }
          .check-goods-type {
            font-size: 13px;
            color: #666666;
            margin-bottom: 5px;
          }
          .check-goods-price {
            font-size: 13px;
            span {
              font-size: 16px;
            }
          }
        }
        .check-num {
          min-width: 80px;
          margin-left: auto;
          margin-bottom: 5px;
          align-self: flex-end;
          display: flex;
          align-items: center;
          justify-content: space-between;
          .btn-reduce {
            width: 20px;
            height: 20px;
            font-weight: 300;
            border-radius: 50%;
            border: 1px solid #5a97f2;
            color: #0151c6;
            display: flex;
            justify-content: center;
            align-items: center;
            box-sizing: border-box;
          }

          .num {
            font-size: 20px;
            font-weight: 500;
          }

          .btn-add {
            width: 20px;
            height: 20px;
            font-weight: 300;
            border-radius: 50%;
            background-color: #0151c6;
            color: #fff;
            display: flex;
            justify-content: center;
            align-items: center;
          }
        }
      }
    }
  }
}
</style>

<style>
.van-badge {
  background-color: #f7b844;
  border: 1px solid #fff;
  border-radius: 50%;
  color: #333;
}
.van-checkbox__icon--checked .van-icon {
  background-color: #143ea9;
  border: 1px solid #143ea9;
}
.van-radio__icon--checked .van-icon {
  background-color: #143ea9;
  border: 1px solid #143ea9;
}
</style>
